package cn.getech.data.development.service.impl;

import cn.getech.data.development.constant.*;
import cn.getech.data.development.controller.search.SearchDetail;
import cn.getech.data.development.entity.ConfConnect;
import cn.getech.data.development.entity.TableFieldInfo;
import cn.getech.data.development.entity.TableInfo;
import cn.getech.data.development.entity.dataMap.BdpTableUseInfo;
import cn.getech.data.development.entity.dataMap.SearchHistory;
import cn.getech.data.development.entity.dataMap.TableInfoSearch;
import cn.getech.data.development.entity.dataMap.TargetSearch;
import cn.getech.data.development.entity.flink.BdpRealTableField;
import cn.getech.data.development.entity.flink.BdpRealTableInfo;
import cn.getech.data.development.mapper.ConfConnectMapper;
import cn.getech.data.development.mapper.dataMap.BdpTableUseInfoMapper;
import cn.getech.data.development.mapper.dataMap.SearchHistoryMapper;
import cn.getech.data.development.mapper.flink.BdpRealTableFieldMapper;
import cn.getech.data.development.mapper.flink.BdpRealTableInfoMapper;
import cn.getech.data.development.model.req.search.DataSearchReq;
import cn.getech.data.development.model.res.dataService.CollectTaskRes;
import cn.getech.data.development.model.res.dataService.DataServiceRes;
import cn.getech.data.development.model.vo.TableStatisticsVO;
import cn.getech.data.development.service.*;
import cn.getech.data.development.utils.DataPermissionUtil;
import cn.getech.data.intelligence.common.exception.RRException;
import cn.getech.data.intelligence.common.utils.ByteConverFormat;
import cn.getech.data.intelligence.common.utils.DateUtils;
import cn.getech.data.intelligence.common.utils.PageUtils;
import cn.getech.system.center.model.dto.SysUserDto;
import cn.getech.system.center.service.SysUserService;
import cn.getech.system.center.utils.ShiroUtils;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("searchHistoryServiceImpl")
public class SearchHistoryServiceImpl extends ServiceImpl<SearchHistoryMapper, SearchHistory> implements SearchHistoryService {

    @Autowired
    private ConfConnectMapper confConnectMapper;
    @Autowired
    private TableStatisticsService tableStatisticsService;
    @Autowired
    private ConfConnectService confConnectService;
    @Autowired
    private BdpTableUseInfoMapper bdpTableUseInfoMapper;
    @Autowired
    private TableFieldInfoService tableFieldInfoService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private BdpRealTableInfoMapper bdpRealTableInfoMapper;
    @Autowired
    private BdpRealTableFieldMapper bdpRealTableFieldMapper;
    @Autowired
    private TableInfoService tableInfoService;
    @Autowired
    private EsCategoryService esCategoryService;

    @Override
    public List<SearchHistory> historyList(SearchHistory param) {
        Long userId = ShiroUtils.getUserId();
        Integer tenantId =ShiroUtils.getTenantId();
        Date date = DateUtils.addDateDays(new Date(), -7);//查询一周的记录
        List<SearchHistory> list = baseMapper.selectList(
                new QueryWrapper<SearchHistory>()
                        .eq("search_type", param.getSearchType())
                        .eq("create_user", userId)
                        .eq("tenant_id", tenantId)
                        .gt("create_time", date).orderByDesc("update_time")
        );
        for (SearchHistory searchHistory : list) {
            if ("tableName".equals(searchHistory.getSearchType())) {
                if (searchHistory.getTableType().equals(1)) {
                    TableInfo table = baseMapper.getTableById(searchHistory.getDataId());
                    if (table != null) {
                        searchHistory.setTableName(table.getTableName());
                    }
                }else {
                    BdpRealTableInfo table = bdpRealTableInfoMapper.selectById(param.getId());
                    if (table != null) {
                        searchHistory.setTableName(table.getTableName());
                    }
                }
            }else if ("targetName".equals(searchHistory.getSearchType())) {
                String targetName = baseMapper.getTargetName(searchHistory.getDataId());
                if (StringUtils.isNotEmpty(targetName)) {
                    searchHistory.setTargetName(targetName);
                }
            }else if ("fieldName".equals(searchHistory.getSearchType())) {
               /* TableFieldInfo field = tableFieldInfoService.getById(searchHistory.getDataId());
                if (field != null) {
                    searchHistory.setFieldName(field.getFieldName());
                }*/
            }
            QueryWrapper<SearchHistory> con = new QueryWrapper<SearchHistory>()
                    .eq("create_user", searchHistory.getCreateUser())
                    .eq("search_type", searchHistory.getSearchType())
                    .eq("tenant_id", searchHistory.getTenantId())
                    .eq("data_id", searchHistory.getDataId());
            if (StringUtils.isNotEmpty(searchHistory.getFieldName())) {
                con.eq("field_name",searchHistory.getFieldName());
            }
            baseMapper.update(searchHistory, con);
        }
        return list;
    }

    @Override
    public void saveHistory(SearchHistory param) {
        Long userId = ShiroUtils.getUserId();
        Integer tenantId = ShiroUtils.getTenantId();
        param.setCreateUser(userId);
        param.setTenantId(tenantId);
        param.setUpdateUser(userId);
        param.setUpdateTime(new Date());
        param.setCreateTime(new Date());
        QueryWrapper<SearchHistory> con = new QueryWrapper<SearchHistory>()
                .eq("create_user", param.getCreateUser())
                .eq("tenant_id", param.getTenantId())
                .eq("search_type", param.getSearchType())
                .eq("data_id", param.getDataId());
        if (StringUtils.isNotEmpty(param.getFieldName())) {
            con.eq("field_name",param.getFieldName());
        }
        if ("tableName".equals(param.getSearchType())) {
            if (param.getTableType().equals(1)) {
                TableInfo table = baseMapper.getTableById(param.getDataId());
                if (table != null) {
                    param.setTableName(table.getTableName());
                }
            }else {
                BdpRealTableInfo table = bdpRealTableInfoMapper.selectById(param.getId());
                if (table != null) {
                    param.setTableName(table.getTableName());
                }
            }
        }else if ("targetName".equals(param.getSearchType())) {
            String targetName = baseMapper.getTargetName(param.getDataId());
            if (StringUtils.isNotEmpty(targetName)) {
                param.setTargetName(targetName);
            }
        }else if ("dataSource".equals(param.getSearchType())) {
            String dataSource = baseMapper.getDataSource(param.getDataId());
            if (StringUtils.isNotEmpty(dataSource)) {
                param.setDataSource(dataSource);
            }
        }else if ("dataService".equals(param.getSearchType())) {
            String dataService = baseMapper.getDataService(param.getDataId());
            if (StringUtils.isNotEmpty(dataService)) {
                param.setDataService(dataService);
            }
        }else if ("collectTask".equals(param.getSearchType())) {
            String collectTask = baseMapper.getCollectTask(param.getDataId());
            if (StringUtils.isNotEmpty(collectTask)) {
                param.setCollectTask(collectTask);
            }
        }
        int num = baseMapper.update(param,con );
        if (num == 0) {
            baseMapper.insert(param);
        }
    }

    @Override
    public Integer saveUseInfo(BdpTableUseInfo param) {
        return bdpTableUseInfoMapper.insertOrUpdateSelective(param);
    }

    @Override
    public JSONObject searchDetail(SearchDetail param) {
        JSONObject data=new JSONObject();
        Long userId = ShiroUtils.getUserId();
        Integer tenantId = ShiroUtils.getTenantId();
        //主题域
        String subjectArea=baseMapper.getSubjectArea(param.getTableType(),param.getId());
        if (YesOrNoEnum.YES.getValue().equals(param.getTableType())) {//离线表
            TableInfo table = baseMapper.getTableById(param.getId());
            if (table!=null){
                Integer num = table.getViewNum();
                if (num != null) {
                    num++;
                } else {
                    num = 1;
                }
                if (YesOrNoEnum.NO.getValue().equals(param.getFlag())) {//需要权限过滤
                    tableInfoService.cheackTables(param.getId(),userId.intValue(),tenantId);
                }
                table.setViewNum(num);
                baseMapper.addViewNum(param.getId(),param.getTableType(),num);
                List<TableFieldInfo> allFieldList;
                IPage<TableFieldInfo> dataPage = new Page<>(1, 999);
                if (YesOrNoEnum.NO.getValue().equals(param.getFlag())) {//需要权限过滤
                    dataPage = tableFieldInfoService.page(dataPage,param.getId());
                    allFieldList=dataPage.getRecords();
                }else{
                    allFieldList= tableFieldInfoService.list(
                            new QueryWrapper<TableFieldInfo>().eq("table_id", param.getId()));
                }
                List<TableFieldInfo> partitionList = allFieldList.stream().filter(
                                s -> YesOrNoEnum.YES.getValue().equals(s.getIsPartition()))
                        .collect(Collectors.toList());
                List<TableFieldInfo> fieldList = allFieldList.stream().filter(
                                s -> !YesOrNoEnum.YES.getValue().equals(s.getIsPartition()))
                        .collect(Collectors.toList());
                if (table.getTotalSize() == null) {
                    table.setTotalSize(0.0);
                }
                table.setTotalSizeStr(ByteConverFormat.convertFormat(table.getTotalSize()));
                table.setSubjectArea(subjectArea);
                data.put("baseInfo",table);
                data.put("storeType", StorageEngineEnum.HIVE.getCode().equals(table.getStoreEngine())?"hive":"kudu");
                Map<String, Object> businessInfo = baseMapper.getBusinessById(param.getId());
                data.put("businessInfo",businessInfo);

                data.put("fieldNum",allFieldList.size());
                data.put("partitionList",partitionList);
                data.put("useFlag", Integer.parseInt(userId.toString()) == table.getCreatePer());
                data.put("fieldList",fieldList);
                TableStatisticsVO storeInfo = tableStatisticsService.saveOfYesterday(param.getId());
                if (CollectionUtils.isNotEmpty(partitionList)) {
                    storeInfo.setPartitionFlag(YesOrNoEnum.YES.getValue());
                }
                data.put("storeInfo", storeInfo);
            }
        }else{ //实时表
            BdpRealTableInfo table = baseMapper.getRealTableById(param.getId());
            //平台管理员是没有租户的  tenantId==null
            if(table == null){
                throw new RRException("表不存在！");
            }
            if (YesOrNoEnum.NO.getValue().equals(param.getFlag())) {
                cheackRealTables(param.getId(),userId.intValue(),tenantId,table);
            }
            Integer num = table.getViewNum();
            if (num != null) {
                num++;
            } else {
                num = 1;
            }
            table.setViewNum(num);
            baseMapper.addViewNum(param.getId(),param.getTableType(),num);
            List<BdpRealTableField> fieldList = bdpRealTableFieldMapper.selectList(
                    new QueryWrapper<BdpRealTableField>().eq("table_id", param.getId()));
            if (RealTableType.INNER.getCode().equals(table.getTableType())
                    && YesOrNoEnum.NO.getValue().equals(param.getFlag()) //需要权限过滤
                    && !userId.equals(table.getCreateUser())
            ) {
                    List<Integer> tableIds = DataPermissionUtil.getApplyRealTableDataIds(userId,
                            PermissionTypeEnum.QUERY.getType());
                    if (!tableIds.contains(param.getId())) {// 申请有查询权限 则字段都有查询权限
                        // 获取角色赋予的权限
                        List<Integer> ids = DataPermissionUtil.getDataIds(PermissionTypeEnum.REAL_TABLE_FILED.getType(),
                                PermissionTypeEnum.QUERY.getType());

                        //  获取 申请的字段权限id
                        ids.addAll(DataPermissionUtil.getCreateFiledIds(table.getId(),userId, StoreTableType.ONLINE.getCode()));
                        if (CollectionUtils.isEmpty(ids)) {
                            ids.add(-1);//无权限
                        }
                        fieldList = fieldList.stream().filter(s -> ids.contains(s.getId())
                                || userId.equals(s.getCreateUser())).collect(Collectors.toList());
                    }
            }
            table.setSubjectArea(subjectArea);
            data.put("baseInfo",table);
            data.put("storeType","kafka");
            Map<String, Object> businessInfo = new HashMap<>();
            if (StringUtils.isNotEmpty(table.getSubjectName())) {
                businessInfo.put("subjectName",
                        table.getSubjectName().replaceAll(",",";"));
            }
            data.put("businessInfo",businessInfo);
            data.put("fieldNum",fieldList.size());
            data.put("fieldList",fieldList);
            data.put("useFlag", userId.equals(table.getCreateUser()));

        }
        data.put("useInfo", bdpTableUseInfoMapper.selectOne(
                new QueryWrapper<BdpTableUseInfo>().eq("table_id", param.getId())
                        .eq("table_type",param.getTableType())
        ));
        return data;
    }

    private void cheackRealTables(Integer id, Integer userId, Integer tenantId, BdpRealTableInfo table) {
        if(table == null){
            throw new RRException("表不存在！");
        }
        //不是平台管理员的权限验证
        if(null != tenantId){
            List<Integer> dataIds = null;
            List<Integer> resourceIds = null;
            if(Objects.equals(1,table.getTableType())){
                //内部部表
                dataIds = DataPermissionUtil.getDataIds(userId.intValue(), PermissionTypeEnum.REAL_TABLE.getType(), PermissionTypeEnum.QUERY.getType());
            }else{
                //外部表
                resourceIds = DataPermissionUtil.getDataIds(userId.intValue(),PermissionTypeEnum.RESOURCE.getType(),
                        PermissionTypeEnum.QUERY.getType());
            }
            //如果是普通用户，还得添加上直接创建的ids
            if(!DataPermissionUtil.isAdmin(userId)){
                //租户管理员的表
                List<BdpRealTableInfo> tableInfos = bdpRealTableInfoMapper.selectList(new LambdaQueryWrapper<BdpRealTableInfo>()
                        .eq(BdpRealTableInfo::getCreateUser, userId).eq(BdpRealTableInfo::getTenantId, tenantId));
                if(CollectionUtil.isNotEmpty(tableInfos)){
                    Set<Integer> ids = tableInfos.stream().map(BdpRealTableInfo::getId).collect(Collectors.toSet());
                    if(dataIds == null){
                        dataIds = new ArrayList<>();
                    }
                    dataIds.addAll(ids);
                    if(resourceIds == null){
                        resourceIds = new ArrayList<>();
                    }
                    Set<Integer> connectIds = tableInfos.stream().map(BdpRealTableInfo::getResourceId).collect(Collectors.toSet());
                    resourceIds.addAll(connectIds);
                }
            }
            //外部表或者是内部表
            if(Objects.equals(1,table.getTableType())){
                if(CollectionUtil.isEmpty(dataIds)){
                    throw new RRException("该用户无权查看当前表的信息！");
                }
                if(!dataIds.contains(id)){
                    throw new RRException("该用户无权查看当前表的信息！");
                }
            }else{
                //外部表
                if(CollectionUtil.isEmpty(resourceIds)){
                    throw new RRException("该用户无权查看当前表的信息！");
                }
                if(!resourceIds.contains(table.getResourceId())){
                    throw new RRException("该用户无权查看当前表的信息！");
                }
            }
        }
    }

    private JSONObject searchTablePage(DataSearchReq params){
        JSONObject data=new JSONObject();
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("fieldName",params.getFieldName());
        paramsMap.put("isOnlyShowCore",params.getIsOnlyShowCore());
        paramsMap.put("limit",params.getLimit());
        paramsMap.put("orderBy",params.getOrderBy());
        paramsMap.put("page",params.getPage());
        paramsMap.put("searchType",params.getSearchType());
        paramsMap.put("dbName",params.getDbName());
        paramsMap.put("projectId",params.getProjectId());
//        Set<String> database= Sets.newHashSet();
//        List<TableInfoSearch> list;
//        if ("fieldName".equals(params.getSearchType())) {
//            list = baseMapper.searchFieldPage(params);
//        } else {
//            list = baseMapper.searchTablePage(params);
//        }
//        Set<Integer> projectIds = Sets.newHashSet();
//        Set<Integer> subjectIds = Sets.newHashSet();
//        for (TableInfoSearch tableInfoSearch : list) {
//            if (StringUtils.isNotEmpty(tableInfoSearch.getDbName())) {
//                database.add(tableInfoSearch.getDbName());
//            }
//            if (StringUtils.isNotEmpty(tableInfoSearch.getProjectIds())) {
//                for (String id : tableInfoSearch.getProjectIds().split(",")) {
//                    projectIds.add(Integer.parseInt(id));
//                }
//            }
//            if (StringUtils.isNotEmpty(tableInfoSearch.getSubjectIds())) {
//                for (String id : tableInfoSearch.getSubjectIds().split(",")) {
//                    subjectIds.add(Integer.parseInt(id));
//                }
//            }
//        }
//        List<Map<String, Object>> procList=Lists.newArrayList();
//        List<Map<String, Object>> subjectList=Lists.newArrayList();
//        if (CollectionUtils.isNotEmpty(projectIds)) {
//            procList = baseMapper.selectProcListList(projectIds);
//        }
//        if (CollectionUtils.isNotEmpty(subjectIds)) {
//            subjectList = baseMapper.selectSubjectList(subjectIds);
//        }
//        List<JSONObject> databases= Lists.newArrayList();
//        for (String s : database) {
//            JSONObject db = new JSONObject();
//            db.put("id", s);
//            db.put("name", s);
//            databases.add(db);
//        }
//        data.put("project",procList);
//        data.put("database",databases);
//        data.put("subject",subjectList);
        IPage<TableInfoSearch> dataPage = new Page<>(params.getPage(), params.getLimit());
        if ("fieldName".equals(params.getSearchType())) {
//            IPage<TableInfoSearch> page = baseMapper.searchFieldPage(dataPage,params);
//            data.put("page",new PageUtils(page));
            Map<String, Object> stringObjectMap = esCategoryService.searchPage(paramsMap);
            Map<String, Object> fieldMap = (Map<String, Object>) stringObjectMap.get("fieldMap");
            data.put("project",fieldMap.get("project"));
            data.put("database",fieldMap.get("database"));
            data.put("page",stringObjectMap);
        } else {
            IPage<TableInfoSearch> page = baseMapper.searchTablePage(dataPage,params);
            data.put("page",new PageUtils(page));
        }
        return  data;
    }

    @Override
    public JSONObject searchPage(DataSearchReq params) {
        Integer tenantId = ShiroUtils.getTenantId();
        params.setTenantId(tenantId);
        if ("targetName".equals(params.getSearchType())) {
            //指标
            return  searchTargetPage(params);
        }  else if("dataSource".equals(params.getSearchType())){
            //数据源
            return  searchDataSourcePage(params);
        }else if("dataService".equals(params.getSearchType())){
            //数据服务
            return  searchDataServicePage(params);
        }else if("collectTask".equals(params.getSearchType())){
            //采集任务
            return  searchCollectTaskPage(params);
        }else {
            //表或者字段
            return  searchTablePage(params);
        }
    }

    private JSONObject searchTargetPage(DataSearchReq params) {
        JSONObject data = new JSONObject();
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("targetName",params.getTargetName());
        paramsMap.put("isOnlyShowCore",params.getIsOnlyShowCore()?2:1);
        paramsMap.put("limit",params.getLimit());
        paramsMap.put("orderBy",params.getOrderBy());
        paramsMap.put("page",params.getPage());
        paramsMap.put("searchType",params.getSearchType());
        paramsMap.put("targetType",params.getTargetType());
        paramsMap.put("tenantId",params.getTenantId());
        paramsMap.put("subjectId",params.getSubjectId());
//        List<TargetSearch> list=baseMapper.searchTargetPage(params);
//        Set<String> targetType= Sets.newHashSet();
//        Set<Integer> subjectIds = Sets.newHashSet();
//        for (TargetSearch targetSearch : list) {
//            if (StringUtils.isNotEmpty(targetSearch.getSubjectIds())) {
//                for (String id : targetSearch.getSubjectIds().split(",")) {
//                    subjectIds.add(Integer.parseInt(id));
//                }
//            }
//            targetType.add(targetSearch.getTargetType());
//        }
//        List<Map<String, Object>> subjectList=Lists.newArrayList();
//        if (CollectionUtils.isNotEmpty(subjectIds)) {
//            subjectList = baseMapper.selectSubjectList(subjectIds);
//        }
//        List<JSONObject> targetTypeList= Lists.newArrayList();
//        for (String s : targetType) {
//            JSONObject db = new JSONObject();
//            db.put("id", s);
//            db.put("name", "1".equals(s) ? "原子指标" : "派生指标");
//            targetTypeList.add(db);
//        }
//        data.put("targetType",targetTypeList);
//        data.put("subject",subjectList);
//        IPage<TargetSearch> dataPage = new Page<>(params.getPage(), params.getLimit());
//        IPage<TargetSearch> page = baseMapper.searchTargetPage(dataPage,params);
//        data.put("page",new PageUtils(page));

        Map<String, Object> stringObjectMap = esCategoryService.searchPage(paramsMap);
        Map<String, Object> targetNameMap = (Map<String, Object>) stringObjectMap.get("targetNameMap");
        data.put("subject",targetNameMap.get("subject"));
        data.put("targetType",targetNameMap.get("targetType"));
        data.put("page",stringObjectMap);
        return data;
    }



    private JSONObject searchDataSourcePage(DataSearchReq params) {
        JSONObject data = new JSONObject();
        Map<String,Object> map = new HashMap<>();
        map.put("create_per", ShiroUtils.getUserId().intValue());
        map.put("sidx", "id");
        map.put("order", "desc");
        if (map.get("list") == null) {
            map.put("connectEnable", 1);
        }
        map.put("typeId",params.getDataSourceType());
        map.put("procId",params.getProjectId());
        map.put("name",params.getDataSource());
        map.put("page",params.getPage());
        map.put("limit",params.getLimit());
        map.put("searchType",params.getSearchType());
        map.put("dataSource",params.getDataSource());
        DataPermissionUtil.putDataFilter(map,
                PermissionTypeEnum.RESOURCE.getType(), PermissionTypeEnum.QUERY.getType());
//        PageUtils page = confConnectService.queryPage(map);
//        filetInfo2((List<ConfConnect>) page.getList());
//        data.put("page",page);
//        List<Map<Long,String>> dataSource = confConnectMapper.selectDataSourceType(map);
//        List<Map<String,Object>> project = confConnectMapper.selectDataSourceProc(map);
//        for(Map amap:dataSource){
//            amap.put("name",dbTypeTransfor((Integer) amap.get("id")));
//        }
//        data.put("dataSource",dataSource);
//        data.put("project",project);
        Map<String, Object> stringObjectMap = esCategoryService.searchPage(map);
        Map<String, Object> dataSourceMap= (Map<String, Object>) stringObjectMap.get("dataSourceMap");
        data.put("dataSource",dataSourceMap.get("dataSource"));
        data.put("project",dataSourceMap.get("project"));
        data.put("page",stringObjectMap);
        return data;
    }

    private JSONObject searchDataServicePage(DataSearchReq params) {
        Map<String, Object> paramsMap = new HashMap<>();
        DataPermissionUtil.putDataFilter(paramsMap,
                PermissionTypeEnum.DATA_SERVICE.getType(), PermissionTypeEnum.QUERY.getType());
        paramsMap.put("dataService",params.getDataService());
        paramsMap.put("dataSourceType",params.getDataSourceType());
        paramsMap.put("serviceGroup",params.getServiceGroup());
        paramsMap.put("searchType",params.getSearchType());
        paramsMap.put("page",params.getPage());
        paramsMap.put("limit",params.getLimit());
//        Page page = new Page();
//        page.setCurrent(params.getPage());
//        page.setSize(params.getLimit());
//        IPage<DataServiceRes> dataServiceResPage = confConnectMapper.searchDataServicePage(page,paramsMap);
//        for(DataServiceRes res:dataServiceResPage.getRecords()){
//            if(res.getTypeId()!=null){
//                res.setTypeName(dbTypeTransfor(res.getTypeId()));
//            }
//        }
        JSONObject data = new JSONObject();
//        data.put("page",new PageUtils(dataServiceResPage));
//        data.put("dataSource",dataSource);
//        data.put("service",service);
//        List<Map<Long,String>> service = confConnectMapper.searchDataServiceGroup(paramsMap);

//        List<Map<Integer,String>> dataSource = confConnectMapper.searchDataServiceSource(paramsMap);
//        for(Map map:dataSource){
//            map.put("name",dbTypeTransfor((Integer) map.get("id")));
//        }
        Map<String, Object> stringObjectMap = esCategoryService.searchPage(paramsMap);
        Map<String, Object> serviceMap = (Map<String, Object>) stringObjectMap.get("serviceMap");
        data.put("page",stringObjectMap);
        data.put("dataSource",serviceMap.get("dataSource"));
        data.put("service",serviceMap.get("service"));
        return data;
    }

    private JSONObject searchCollectTaskPage(DataSearchReq params) {
        Map<String, Object> paramsMap = new HashMap<>();
        //采集任务的权限是从数据源权限来的
        DataPermissionUtil.putDataFilter(paramsMap,
                PermissionTypeEnum.RESOURCE.getType(), PermissionTypeEnum.QUERY.getType());
        paramsMap.put("collectTask",params.getCollectTask());
        paramsMap.put("dataSourceType",params.getDataSourceType());
        paramsMap.put("taskType",params.getTaskType());
        paramsMap.put("searchType",params.getSearchType());
        paramsMap.put("page",params.getPage());
        paramsMap.put("limit",params.getLimit());
        //没有权限的也要展示
//        paramsMap.put("ids",null);
        JSONObject data = new JSONObject();
//        Page page = new Page();
//        page.setCurrent(params.getPage());
//        page.setSize(params.getLimit());
//        IPage<CollectTaskRes> collectTaskPage = confConnectMapper.searchCollectTaskPage(page,paramsMap);
//        for(CollectTaskRes res:collectTaskPage.getRecords()){
//            if(res.getSourceTypeId()!=null){
//                res.setSourceType(dbTypeTransfor(res.getSourceTypeId()));
//            }
//            ModuleDto moduleDto = confConnectMapper.searchModule(res.getOwnModule());
//            Integer parentId = moduleDto.getId();
//            String metadataBelongs = moduleDto.getName();
//            while (parentId>0){
//                ModuleDto amoduleDto = confConnectMapper.searchModule(parentId);
//                if(amoduleDto!=null){
//                    parentId = amoduleDto.getId();
//                    metadataBelongs = amoduleDto.getName()+"/"+metadataBelongs;
//                }else {
//                    parentId=-1;
//                }
//            }
//            switch (res.getTaskTypeId()){
//                case 0:res.setTaskType("手动采集");break;
//                case 1:res.setTaskType("自动采集");break;
//                case 2:res.setTaskType("接口");break;
//            }
//            res.setMetadataBelongs(metadataBelongs);
//        }
//        data.put("page",new PageUtils(collectTaskPage));
        List<Map<Integer,String>> dataSource = confConnectMapper.searchCollectTaskSource(paramsMap);
        for(Map map:dataSource){
            map.put("name",dbTypeTransfor(Integer.valueOf((String) map.get("id")) ));
        }
//        data.put("dataSource",dataSource);
        List<Map<Integer,String>> task = confConnectMapper.searchCollectTaskType(paramsMap);
        for(Map map:task){
            Integer id =(Integer) map.get("id");
            switch (id){
                case 0:map.put("name","手动采集");break;
                case 1:map.put("name","自动采集");break;
                case 2:map.put("name","接口");break;
            }
        }
//        data.put("task",task);

        Map<String, Object> stringObjectMap = esCategoryService.searchPage(paramsMap);
        Map<String, Object> taskMap = (Map<String, Object>) stringObjectMap.get("taskMap");
        data.put("page",stringObjectMap);
        data.put("task",taskMap.get("task"));
        data.put("dataSource",taskMap.get("dataSource"));
        return data;
    }

    private void filetInfo2(List<ConfConnect> confConnectList) {
        List<SysUserDto> userList = sysUserService.listAllUsers();
        Map<Long, String> userMap = userList.stream().collect(
                Collectors.toMap(SysUserDto::getUserId, SysUserDto::getUsername));
        for (ConfConnect confConnect : confConnectList) {
            String info = null;
            if (ConnectTypeEnum.Kafka.getCode().equals(confConnect.getTypeId())) {
                info = String.format("%s | %s", confConnect.getKafkaUrl(), confConnect.getTopic());
            } else if (ConnectTypeEnum.FTP.getCode().equals(confConnect.getTypeId())) {
                info = String.format("%s:%s", confConnect.getHost(), confConnect.getPort());
            } else if (ConnectTypeEnum.Sap.getCode().equals(confConnect.getTypeId())) {
                info = String.format("%s:%s", confConnect.getHost(), confConnect.getPort());
            } else if (ConnectTypeEnum.JieKou.getCode().equals(confConnect.getTypeId())) {
                info = String.format("%s", confConnect.getInterfaceUrl());
            } else if (ConnectTypeEnum.WebService.getCode().equals(confConnect.getTypeId())) {
                if (Objects.equals(3, confConnect.getRequestType())) {
                    info = String.format("%s | %s", confConnect.getWebServiceUrl(), "post-raw");
                } else {
                    info = String.format("%s | %s", confConnect.getWebServiceUrl(), confConnect.getFunctionName());
                }
            } else if (ConnectTypeEnum.OracleNTS.getCode().equals(confConnect.getTypeId())) {
                info = String.format("%s", confConnect.getOracleNtsUrl());
            } else {
                if (StringUtils.isEmpty(confConnect.getDbname()))
                    info = String.format("%s:%s", confConnect.getHost(), confConnect.getPort());
                else
                    info = String.format("%s:%s | %s", confConnect.getHost(), confConnect.getPort(), confConnect.getDbname());
            }
            confConnect.setInfo(info);
            if (confConnect.getCreatePer() != null) {
                Long userId = Long.valueOf(confConnect.getCreatePer());
                confConnect.setCreatePerName(userMap.get(userId));
            }

            if (confConnect.getModPer() != null) {
                Long userId = Long.valueOf(confConnect.getModPer());
                confConnect.setModPerName(userMap.get(userId));
            }

            StringBuilder builder = new StringBuilder();
            if (StringUtils.isNotEmpty(confConnect.getProcNames())) {
                builder.append("关联的项目:<br/>").append(confConnect.getProcNames()).append("<br/>");
            }
            if (StringUtils.isNotEmpty(confConnect.getTaskNames())) {
                builder.append("关联的元数据采集任务:<br/>").append(confConnect.getTaskNames()).append("<br/>");
            }
            if (StringUtils.isNotEmpty(confConnect.getRuleNames())) {
                builder.append("关联的质量规则:<br/>").append(confConnect.getRuleNames()).append("<br/>");
            }
            if (StringUtils.isNotEmpty(confConnect.getServiceNames())) {
                builder.append("关联的数据服务:<br/>").append(confConnect.getServiceNames()).append("<br/>");
            }

            if (StringUtils.isNotEmpty(confConnect.getSyncTaskNames())) {
                builder.append("关联的整库同步任务:<br/>").append(confConnect.getSyncTaskNames()).append("<br/>");
            }

            confConnect.setAppState(2);//1:使用中 2:未使用
            if (builder.length() > 0) {
                confConnect.setAppState(1);
                confConnect.setAppStateStr("使用中");
            }else {
                confConnect.setAppStateStr("未使用");
            }
            if(confConnect.getConnectStatus()!=null&&confConnect.getConnectStatus()==1){
                confConnect.setConnectStatusStr("正常");
            }else {
                confConnect.setConnectStatusStr("失败");
            }
            confConnect.setRelationContent(builder.toString());
            confConnect.setTypeName(dbTypeTransfor(confConnect.getTypeId()));
        }
    }

    private String dbTypeTransfor(Integer typeId){
        if(typeId==null){
            return null;
        }
        switch (typeId){
            case 1:return "MySQL";
            case 2:return "Oracle";
            case 3:return "SQL_Server";
            case 4:return "PostgreSQL";
            case 5:return "FTP";
            case 6:return "Kafka";
            case 7:return "JieKou";
            case 8:return "Sap";
            case 9:return "WebService";
            case 10:return "SAPHANA";
            case 11:return "Hive";
            case 12:return "ElasticSearch";
            case 13:return "HBase";
            case 14:return "Kudu";
            case 15:return "ClickHouse";
            case 16:return "Oracle";
            case 17:return "MongoDB";
            case 18:return "SFTP";
        }
        return null;
    }

}


